package com.sheng.leetcode.year2023.month11.day06;

import org.junit.Test;

/**
 * @author by ls
 * @date 2023/11/6
 * <p>
 * 318. 最大单词长度乘积<p>
 * <p>
 * 给你一个字符串数组 words ，找出并返回 length(words[i]) * length(words[j]) 的最大值，<p>
 * 并且这两个单词不含有公共字母。如果不存在这样的两个单词，返回 0 。<p>
 * <p>
 * 示例 1：<p>
 * 输入：words = ["abcw","baz","foo","bar","xtfn","abcdef"]<p>
 * 输出：16<p>
 * 解释：这两个单词为 "abcw", "xtfn"。<p>
 * <p>
 * 示例 2：<p>
 * 输入：words = ["a","ab","abc","d","cd","bcd","abcd"]<p>
 * 输出：4<p>
 * 解释：这两个单词为 "ab", "cd"。<p>
 * <p>
 * 示例 3：<p>
 * 输入：words = ["a","aa","aaa","aaaa"]<p>
 * 输出：0<p>
 * 解释：不存在这样的两个单词。<p>
 * <p>
 * 提示：<p>
 * 2 <= words.length <= 1000<p>
 * 1 <= words[i].length <= 1000<p>
 * words[i] 仅包含小写字母<p>
 */
public class LeetCode0318 {

    @Test
    public void test01() {
        String[] words = {"abcw", "baz", "foo", "bar", "xtfn", "abcdef"};
//        String[] words = {"a", "ab", "abc", "d", "cd", "bcd", "abcd"};
//        String[] words = {"a", "aa", "aaa", "aaaa"};
        System.out.println(new Solution().maxProduct(words));
    }
}

class Solution {
    public int maxProduct(String[] words) {
        int ans = 0;
        int n = words.length;
        int[] mask = new int[n];
        for (int i = 0; i < n; ++i) {
            for (char c : words[i].toCharArray()) {
                // 如果两个字符串没有公共字母，那么这两个字符串对应的二进制数的按位与的结果为 0
                mask[i] |= 1 << (c - 'a');
            }
            for (int j = 0; j < i; ++j) {
                if ((mask[i] & mask[j]) == 0) {
                    ans = Math.max(ans, words[i].length() * words[j].length());
                }
            }
        }
        return ans;
    }
}
